package com.ruoyi.develop.invoice.utils;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.develop.invoice.entity.InvoiceRegexEnum;
import com.ruoyi.develop.invoice.entity.NewInvoice;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * 处理电子发票识别类
 * @author b16mt
 */
public class NewPdfInvoiceExtractor {
    public static NewInvoice extract(File file) throws IOException {
        NewInvoice invoice = new NewInvoice();
        PDDocument doc = PDDocument.load(file);
//        PDPage firstPage = doc.getPage(0);

//        int pageWidth = Math.round(firstPage.getCropBox().getWidth());

        PDFTextStripper textStripper = new PDFTextStripper();
        textStripper.setSortByPosition(true);

        String fullText = textStripper.getText(doc);

//        if (firstPage.getRotation() != 0) {
//            pageWidth = Math.round(firstPage.getCropBox().getHeight());
//        }

        String allText = replace(fullText).replaceAll("（", "(").replaceAll("）", ")").replaceAll("￥", "¥");

        {
            Pattern pattern = Pattern.compile(InvoiceRegexEnum.REGULAR_A_NEW.getRegex());
            Pattern patternNumber = Pattern.compile(InvoiceRegexEnum.REGULAR_A_1.getRegex());
            Pattern patternDate = Pattern.compile(InvoiceRegexEnum.REGULAR_A_2.getRegex());
            Matcher matcher = pattern.matcher(allText);
            while (matcher.find()) {
                if (matcher.group("number") != null) {
                    invoice.setNumber(matcher.group("number"));
                } else if (matcher.group("date") != null) {
                    String rawDate = matcher.group("date");
                    try {
                        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
                        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                        Date parsedDate = inputDateFormat.parse(rawDate);
                        String formattedDate = outputDateFormat.format(parsedDate);
                        invoice.setDate(formattedDate);
                    } catch (ParseException e) {
                        System.out.println("无法解析日期：" + rawDate);
                    }
                } else if (matcher.group("name") != null){
                    invoice.setSellerName(matcher.group("name"));
                }

                if (matcher.group("number") == null){
                    Matcher matcher2 = patternNumber.matcher(allText);
                    if (matcher2.find()) {
                        invoice.setNumber(matcher2.group("number"));
                    }
                }
                if (matcher.group("date") == null){
                    Matcher matcher3 = patternDate.matcher(allText);
                    if (matcher3.find()) {
                        String rawDate = matcher3.group("date");
                        try {
                            SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyyMM月dd日");
                            SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                            Date parsedDate = inputDateFormat.parse(rawDate);
                            String formattedDate = outputDateFormat.format(parsedDate);

                            invoice.setDate(formattedDate);
                        } catch (Exception e) {
                            System.out.println("无法解析日期：" + rawDate);
                        }
                    }
                }
            }
        }
        //获取不到发票号码按照老版发票处理
        if(StringUtils.isBlank(invoice.getNumber())){
            return null;
        }

        {
            Pattern pattern = Pattern.compile(InvoiceRegexEnum.REGULAR_B.getRegex());
            Matcher matcher = pattern.matcher(allText);
            if (matcher.find()) {
                try {
                    invoice.setAmount(new BigDecimal(matcher.group("amount")));
                } catch (Exception e) {
                    // 不处理
                }
                try {
                    invoice.setTaxAmount(new BigDecimal(matcher.group("taxAmount")));
                } catch (Exception e) {
                    invoice.setTaxAmount(new BigDecimal(0));
                }
            }
        }

        if (null == invoice.getAmount()) {
            Pattern pattern = Pattern.compile(InvoiceRegexEnum.REGULAR_B_1.getRegex());
            Matcher matcher = pattern.matcher(fullText);
            if (matcher.find()) {
                try {
                    invoice.setAmount(new BigDecimal(matcher.group("amount")));
                } catch (Exception e) {
                    invoice.setAmount(new BigDecimal(0));
                }
                try {
                    invoice.setTaxAmount(new BigDecimal(matcher.group("taxAmount")));
                } catch (Exception e) {
                    invoice.setTaxAmount(new BigDecimal(0));
                }
            }
        }
        invoice.setTotalAmount(invoice.getAmount().add(invoice.getTaxAmount()));

        if (null == invoice.getInReserve2()) {
            Pattern pattern = Pattern.compile(InvoiceRegexEnum.REGULAR_E.getRegex());
            Matcher matcher = pattern.matcher(fullText);
            if (matcher.find()) {
                try {
                    invoice.setInReserve2("普票");
                } catch (Exception e) {
                    System.out.println("无法解析日期：" + matcher.group("p"));
                }
            }else {
                Pattern pattern1 = Pattern.compile(InvoiceRegexEnum.REGULAR_E_1.getRegex());
                Matcher matcher1 = pattern1.matcher(fullText);
                if (matcher1.find()) {
                    try {
                        invoice.setInReserve2("专票");
                    } catch (Exception e) {
                        System.out.println("无法解析日期：" + matcher1.group("p"));
                    }
                }
            }
        }

        if (null == invoice.getContent()) {
            Pattern pattern = Pattern.compile(InvoiceRegexEnum.REGULAR_B_C.getRegex());
            Matcher matcher = pattern.matcher(fullText);
            if (matcher.find()) {
                try {
                    invoice.setContent(matcher.group(1));
                } catch (Exception e) {
                    invoice.setContent(null);
                }
            }
        }
        return invoice;

    }

    /**
     * 替换字符串中的空格、全角空格、冒号和特殊空白字符为标准字符。
     * @param str 要进行替换的字符串
     * @return 替换后的字符串
     */
    private static String replace(String str) {
        return str.replaceAll(" ", "").replaceAll("　", "").replaceAll("：", ":").replaceAll(" ", "");
    }
}
